package com.web.websocket;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description
 * @author: yx-0173
 * @date: 2021-06-09 09:50
 **/
@Controller("web-socket-system")
@RequestMapping("/api/socket")
public class SystemController {


    /**
     * 页面请求
     * @param userId
     * @return
     */
    @GetMapping("/index/{userId}")
    public ModelAndView socket(@PathVariable String userId) {
        ModelAndView mav = new ModelAndView("/socket1");
        mav.addObject("userId", userId);
        return mav;
    }

    /**
     * 推送数据接口
     *
     * @param cid
     * @param message
     * @return
     */
    @ResponseBody
    @RequestMapping("/socket/push")
    public Map<String, Object> pushToWeb(@RequestParam("cid") String cid, @RequestParam("message") String message) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            WebSocketServer.sendInfo(message, cid);
            result.put("code", cid);
            result.put("msg", message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
